package com.labofjet.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.labofjet.common.dto.ContextDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * json和java对象相互转化
 */
public class JSONUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);

	private static final ObjectMapper OM;

	static {
		OM = new ObjectMapper();
		OM.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);// java没有json的某些字段不报错
	}

	public static <T> T stringToDto(String from, Class<T> to) {
		T t = null;
		try {
			t = OM.readValue(from, to);
		} catch (IOException e) {
			throw new IllegalArgumentException("json反序列化错误", e);
		}
		return t;
	}

	public static String dtoToString(Object o) {
		String s = null;
		try {
			s = OM.writeValueAsString(o);
		} catch (JsonProcessingException e) {
			throw new IllegalArgumentException("json序列化错误", e);
		}
		return s;
	}

	public static <T> T getRequestData(ContextDto contextDto, Class<T> to) {
		try {
			return OM.treeToValue(contextDto.getRequestData(), to);
		} catch (JsonProcessingException e) {
			throw new IllegalArgumentException("RequestData转化成JavaBean出错", e);
		}
	}

	public static ObjectMapper getObjectMapper() {
		return OM;
	}

}
